package com.kokomi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kokomi.pojo.Address;
import com.kokomi.service.AddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/Address")
@Slf4j
public class AddressController {


    @Autowired
    private AddressService addressService;


    /**
     * 添加地址
     */
    @PostMapping("/add")
    public ResponseEntity addAddress(@RequestBody Address address){
        if(address.getIsDefault() == 1){
            // 修改默认地址为0
            Address updateAddress = new Address();
            updateAddress.setIsDefault(0);
            addressService.getBaseMapper().update(updateAddress,new QueryWrapper<Address>().eq("user_id",address.getUserId()).eq("is_default",1));
            addressService.save(address);
        }else{
            addressService.save(address);
        }

        return ResponseEntity.ok("添加成功");
    }

    @GetMapping("/get/{userId}")
    public ResponseEntity getAddress(@PathVariable("userId") Long userId){
        // 根据用户id查询地址
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<Address> list = addressService.list(queryWrapper);
        return ResponseEntity.ok(list);
    }

}
